import {
    myRequest,
} from './http.js'

let code = ""
let openId = ""
let unionId = ""
let wxUserInfo = ""

function logins() {
    wx.login({
        success(res) {
            code = res.code;
            getOpenId();
        },
    });
}
async function getOpenId() {
    const data = await myRequest({
        url: "index/getOpenId",
        method: "POST",
        data: {
            code: code,
        },
    });
    openId = data.data.data.openId;
    unionId = data.data.data.unionId;
    wx.showModal({
        title: "温馨提示",
        content: "正在请求您的个人信息",
        success(res) {
            if (res.confirm) {
                wx.getUserProfile({
                    desc: "获取你的昵称、头像、地区及性别",
                    success: (res) => {
                        wxUserInfo = res.userInfo;
                        adduser();
                    },
                    fail: (res) => {
                        //拒绝授权
                        uni.showToast({
                            title: "您拒绝了请求",
                            icon: "none",
                        });
                        return;
                    },
                });
            } else if (res.cancel) {
                uni.showToast({
                    title: "您拒绝了请求",
                    icon: "none",
                });
                return;
            }
        },
    });
}

async function adduser() {
    const datas = await myRequest({
        url: "user/add_users",
        method: "POST",
        data: {
            avatarUrl: wxUserInfo.avatarUrl,
            nickname: wxUserInfo.nickName,
            openId: openId,
            gender: wxUserInfo.gender,
            province: wxUserInfo.province,
            country: wxUserInfo.country,
            city: wxUserInfo.city,
            unionId: unionId,
            inviteCode: "",
            fromByXcx: 1,
        },
    });
    if (datas.data.code == 1) {
        uni.setStorageSync("token", datas.data.data.token);
        uni.setStorageSync("user", datas.data.data);
        getuserInfo();
    }
}
// 获取用户信息
async function getuserInfo() {
    const res = await myRequest({
        url: "user/getUserInfo",
        method: "GET",
        data: {},
    });
    if (res.data.code == 1) {
        uni.switchTab({
            url: "../pages/index/index",
        });
        uni.setStorageSync("userInfo", res.data.data);
    }
}
module.exports = {
    logins,
}